package priv.blackbibo.application.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.xml.sax.Attributes;
import org.xml.sax.DocumentHandler;
import org.xml.sax.HandlerBase;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import priv.blackbibo.application.R;
import priv.blackbibo.application.domain.BoxTool;
import priv.blackbibo.application.receiver.PluginReceiver;

public class BoxTollActivity extends BaseActivity {

    private String TAG = "BoxTollActivity";

    private GridLayout content = null;

    public static final int DISABLE_EXPAND = 0x00010000;//4.2以上的整形标识
    public static final int DISABLE_EXPAND_LOW = 0x00000001;//4.2以下的整形标识
    public static final int DISABLE_NONE = 0x00000000;//取消StatusBar所有disable属性，即还原到最最原始状态

    private void unBanStatusBar() {//利用反射解除状态栏禁止下拉
        @SuppressLint("WrongConstant") Object service = getSystemService("statusbar");
        try {
            Class<?> statusBarManager = Class.forName
                    ("android.app.StatusBarManager");
            Method expand = statusBarManager.getMethod("disable", int.class);
            expand.invoke(service, DISABLE_NONE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setStatusBarDisable(int disable_status) {//调用statusBar的disable方法
        @SuppressLint("WrongConstant") Object service = getSystemService("statusbar");
        try {
            Class<?> statusBarManager = Class.forName
                    ("android.app.StatusBarManager");
            Method expand = statusBarManager.getMethod("disable", int.class);
            expand.invoke(service, disable_status);
        } catch (Exception e) {
            unBanStatusBar();
            e.printStackTrace();
        }
    }
    private void banStatusBar() {//禁止statusbar下拉，适配了高低版本
        requestPermissions(new String[]{Manifest.permission.STATUS_BAR},1);
        int currentApiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentApiVersion <= 16) {
            setStatusBarDisable(DISABLE_EXPAND_LOW);
        } else {
            setStatusBarDisable(DISABLE_EXPAND);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_box_toll);

        Point point = new Point();
        getWindowManager().getDefaultDisplay().getSize(point);

        banStatusBar();

        content = findViewById(R.id.content);
        InputStream inputStream = getResources().openRawResource(R.raw.box);
        try {
            /**【创建解析器】**/
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser saxParser = spf.newSAXParser();
            XmlContentHandler handler = new XmlContentHandler();
            saxParser.parse(inputStream, handler);
            inputStream.close();
            List<BoxTool> boxTools = handler.getTools();
            int columnCount = content.getColumnCount();
            for (BoxTool boxTool : boxTools) {
                View view = LinearLayout.inflate(this, R.layout.tool, null);
                TextView name = view.findViewById(R.id.name);
                TextView action = view.findViewById(R.id.action);
                ImageView imageView = view.findViewById(R.id.icon);
                name.setText(boxTool.getName());
                action.setText(boxTool.getAction());
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(point.x / columnCount,point.x / columnCount);
                view.setLayoutParams(layoutParams);
                view.setOnClickListener((v)->{
                    Class clazz = null;
                    try {
                        clazz = Class.forName(boxTool.getAction().trim());
                        Intent intent = new Intent(getApplicationContext(),clazz);
                        startActivity(intent);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                });
                content.addView(view);
            }

            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("android.intent.action.HEADSET_PLUG");

            registerReceiver(new PluginReceiver(), intentFilter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class XmlContentHandler extends DefaultHandler {

        List<BoxTool> boxTools = null;

        BoxTool boxTool = null;

        String tagName = null;

        List<BoxTool> getTools(){
            return boxTools;
        }

        @Override
        public void startDocument() throws SAXException {
            boxTools = new LinkedList<>();
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if (localName.equals("tool")){
                boxTool = new BoxTool();
            }
            tagName = localName;
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            if (tagName == null) {
                return;
            }
            String currentValue = String.valueOf(Arrays.copyOfRange(ch, start, length));
            if (tagName.equals("name")) {
                boxTool.setName(currentValue);
            } else if (tagName.equals("action")) {
                boxTool.setAction(currentValue);
            } else if (tagName.equals("icon")) {
                boxTool.setIcon(currentValue);
            }else {

            }
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            if (localName.equals("tool")) {
                boxTools.add(boxTool);
            }
            tagName = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            Log.d(TAG, "onKeyDown: back");
            return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }

}
